package com.pxst.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import com.pxst.exception.PlugsException;

/** 
 * 插件工具类
* @author yangxy
* @version 创建时间：2023年8月30日 下午3:15:43 
*/
@Component
public class PlugsUtils {
	@Autowired
	private ApplicationContext applicationContext;
	
	/**
	 * 调用插件方法
	* @author yangxy
	* @version 创建时间：2023年8月30日 下午3:19:53 
	* @param beanName 插件bean名称、
	* @param excuteMethod 插件执行方法
	* @param paramVal 参数列表(插件方法不用参数是传空)
	* @return
	 */
	public Object plugsExec(String beanName, String excuteMethod, List<Object> paramVal) {
		Object obj = applicationContext.getBean(beanName);
		try {
			if(ObjectUtils.isEmpty(paramVal)) {
				paramVal = Lists.newArrayList();
			}
			
			Class<?>[] paramType = new Class<?>[paramVal.size()];
			for(int i=0;i<paramVal.size();i++) {
				paramType[i] = paramVal.get(i).getClass();
			}

			Method method = obj.getClass().getMethod(excuteMethod, paramType);
			Object[] objParams = paramVal.toArray(new Object[paramVal.size()]);
			Object invoke = method.invoke(obj,objParams);
			return invoke;
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new PlugsException("插件执行异常");
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new PlugsException("插件执行异常");
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
			throw new PlugsException("插件执行异常");
		}
	}

}
